<script setup lang="ts">
import { reactive, ref } from "vue";
import { putArticleAPI } from "@/api/creation.ts";
import { ElMessage, type FormInstance } from "element-plus";
import { ArticleRules } from "@/view/Article/utils/rules.ts";

const dialogTableVisible = ref(false)
const emit = defineEmits(['getData'])
const ruleFormRef = ref<FormInstance>()
const id = ref()
const editForm = reactive({
  title: '',
  views: '',
  diggs: ''
})

// 初始化
const init = (row: any) => {
  id.value = row._id
  editForm.title = row.title
  editForm.views = row.views
  editForm.diggs = row.diggs
  dialogTableVisible.value = true
}

// 取消
const handleCancel = () => {
  dialogTableVisible.value = false
}

// 确认
const handleCommit = () => {
  ruleFormRef.value?.validate(async valid => {
    if (valid) {
      const res: any = await putArticleAPI(id.value, editForm)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '修改成功'
        })
      }
      emit('getData')
      handleCancel()
    }
  })
}

defineExpose({
  init
})
</script>

<template>
  <div>
    <el-dialog v-model="dialogTableVisible" title="编辑文章" width="40%">
      <el-form ref="ruleFormRef"
               :rules="ArticleRules"
               :model="editForm">
        <el-form-item label="标题" prop="=title">
          <el-input v-model="editForm.title"/>
        </el-form-item>
        <el-form-item label="浏览量" prop="views">
          <el-input v-model="editForm.views"/>
        </el-form-item>
        <el-form-item label="点赞量" prop="diggs">
          <el-input v-model="editForm.diggs"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleCommit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>
